<template>
  <div class="photobox">
    <img :src="imge" class="photoCropping" ref="photo" />
    <!-- <van-image class="photoCropping" :src="imge" /> -->
    <div class="nav-bar">
      <van-button type="default" @click="$emit('closer', false)"
        >取消</van-button
      >
      <van-button type="default" @click="posetuserimge">完成</van-button>
    </div>
  </div>
</template>

<script>
import "cropperjs/dist/cropper.css";
import Cropper from "cropperjs";
import { setuserimge } from "@/api/user.js";
export default {
  data() {
    return {
      cropper: null,
    };
  },
  props: {
    imge: {
      type: [String, Object],
      require: true,
    },
    photoshow: {
      type: Boolean,
    },
  },

  mounted() {
    const image = this.$refs.photo;
    this.cropper = new Cropper(image, {
      viewMode: 1,
      dragMode: "move",
      background: false,
      aspectRatio: 1,
      autoCropArea: 1,
      cropBoxMovable: false,
      cropBoxResizable: false,
      movable: true,
      guides: true,
    });
  },
  methods: {
    posetuserimge() {
      this.cropper.getCroppedCanvas().toBlob(
        async (blob) => {
          //因为   Content-Type：	multipart/form-data
          //所以 设置发送的数据格式 formData
          const formData = new FormData();
          formData.append("photo", blob);
          // console.log(formData);
          // 发送请求
          try {
            this.$toast.loading({
              message: "上传中...",
              forbidClick: true,
              duration: 0, // 持续展示 toast
            });
            const { data: res } = await setuserimge(formData);
            console.log(res);
            this.$toast.success("成功");
            this.$emit("updata-photo", res.data.photo);
            // console.log(res);
          } catch (err) {
            this.$toast.fail("失败文案");
          }
        } /*, 'image/png' */
      );
    },
  },
};
</script>

<style scoped lang="less">
.photobox {
  display: flex;
  height: 100%;
  .photoCropping {
    max-width: 100%;
    display: block;
  }
  .nav-bar {
    width: 100%;
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: space-between;
    color: #fff;
    font-size: 50px;
  }
}
</style>